package com.dingreading.cloud.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.dingreading.cloud.admin.dto.ShopCartStatDto;
import com.dingreading.cloud.admin.entity.Stores;
import com.dingreading.cloud.admin.service.ShopCartService;
import com.dingreading.cloud.admin.service.StoresService;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.EnumOperationType;
import com.dingreading.cloud.common.util.excel.ExcelHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/goodsStat")
@Api(tags = "商品统计")
public class GoodsStatController {

    @Resource
    private StoresService storesService;
    @Resource
    private ShopCartService shopCartService;


    /**
     * 运营类型 100自营  80联营  50品牌加盟  40产品加盟  20课程合作（悦读吧）
     */
    private String getOperationTypeName(Integer operationType){
        if (operationType!=null) {
            return EnumOperationType.getTypeName(operationType);
        }
        return "";
    }

    @ApiOperation(value = "合作校采购商品明细")
    @PostMapping(value = "/storeBuyGoodsStat", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void storeBuyGoodsStat(
            HttpServletResponse response,
            @ApiParam(value = "开始日期") @RequestParam(value = "beginDate") String beginDate,
            @ApiParam(value = "结束日期") @RequestParam(value = "endDate") String endDate
    ) throws Exception {
        List<ShopCartStatDto> list = shopCartService.storeBuyGoodsStat(beginDate, endDate);
        if (CollectionUtils.isEmpty(list))
            throw new DescribeException("没有查询到数据");

        // 表格头部列的数据
        List<List<String>> headList = new ArrayList<>();
        // 表格第一列默认是门店名称
        headList.add(Collections.singletonList("门店名称"));
        headList.add(Collections.singletonList("门店类型"));
        headList.add(Collections.singletonList("订单号"));
        headList.add(Collections.singletonList("订单类型"));
        headList.add(Collections.singletonList("商品名称"));
        headList.add(Collections.singletonList("商品规格名称"));
        headList.add(Collections.singletonList("商品单价"));
        headList.add(Collections.singletonList("购买数量"));
        headList.add(Collections.singletonList("购买金额"));
        headList.add(Collections.singletonList("支付时间"));
        // 表格内的数据
        List<List<Object>> dataList = new ArrayList<>();

        Map<String, List<ShopCartStatDto>> map = list.stream()
                .collect(Collectors.groupingBy(ShopCartStatDto::getStoreUid, LinkedHashMap::new, Collectors.toList()));

        Set<String> strings = map.keySet();
        List<Stores> storesList = storesService.getByUids(new ArrayList<>(strings));
        if (CollectionUtils.isEmpty(storesList))
            throw new DescribeException("没有查询到门店");
        Map<String, Integer> storeMap = storesList.stream().collect(Collectors.toMap(Stores::getUid, Stores::getOperationType));

        for (Map.Entry<String, List<ShopCartStatDto>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<ShopCartStatDto> value = entry.getValue();

            Integer operationType = storeMap.get(key);
            String operationTypeName = getOperationTypeName(operationType);

            for (ShopCartStatDto shopCart : value) {
                List<Object> data = new ArrayList<>();
                data.add(shopCart.getStoreName());
                data.add(operationTypeName);
                data.add(shopCart.getCode());
                data.add(shopCart.getType().equals(3) ? "赠品" : "商城下单");
                data.add(shopCart.getGoodsName());
                data.add(shopCart.getGoodsTypeName());
                data.add(shopCart.getUnitPrice());
                data.add(shopCart.getBuyNum());
                data.add(shopCart.getPrice());
                data.add(shopCart.getPayTimes());

                dataList.add(data);
            }
            dataList.add(new ArrayList<>());
        }

        // 导出授权码
        String fileName = "合作校采购商品明细" + beginDate + "-" + endDate;
        EasyExcel.write(ExcelHandler.getOutputStream(fileName, response))
                .head(headList).sheet("合作校采购商品明细")
                .doWrite(dataList);
    }

    @ApiOperation(value = "商品的销售数量明细")
    @PostMapping(value = "/goodsSaleInfo", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void goodsSaleInfo(
            HttpServletResponse response,
            @ApiParam(value = "开始日期") @RequestParam(value = "beginDate") String beginDate,
            @ApiParam(value = "结束日期") @RequestParam(value = "endDate") String endDate
    ) throws Exception {
        List<ShopCartStatDto> list = shopCartService.storeBuyGoodsStat(beginDate, endDate);
        if (CollectionUtils.isEmpty(list))
            throw new DescribeException("没有查询到数据");

        List<String> storeUids = list.stream().map(ShopCartStatDto::getStoreUid).distinct().collect(Collectors.toList());
        List<Stores> storesList = storesService.getByUids(storeUids);
        if (CollectionUtils.isEmpty(storesList))
            throw new DescribeException("没有查询到门店");
        Map<String, Integer> storeMap = storesList.stream().collect(Collectors.toMap(Stores::getUid, Stores::getOperationType));

        Map<String, String> storeOperationTypeMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : storeMap.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            String operationTypeName = getOperationTypeName(value);
            storeOperationTypeMap.put(key,operationTypeName);
        }

        // 表格头部列的数据
        List<List<String>> headList = new ArrayList<>();
        // 表格第一列默认是门店名称
        headList.add(Collections.singletonList("商品名称"));
        headList.add(Collections.singletonList("商品规格名称"));
        headList.add(Collections.singletonList("门店名称"));
        headList.add(Collections.singletonList("门店类型"));
        headList.add(Collections.singletonList("订单号"));
        headList.add(Collections.singletonList("订单类型"));
        headList.add(Collections.singletonList("商品单价"));
        headList.add(Collections.singletonList("购买数量"));
        headList.add(Collections.singletonList("购买金额"));
        headList.add(Collections.singletonList("支付时间"));
        // 表格内的数据
        List<List<Object>> dataList = new ArrayList<>();

        LinkedHashMap<Long, List<ShopCartStatDto>> map = list.stream()
                .collect(Collectors.groupingBy(ShopCartStatDto::getGoodsId, LinkedHashMap::new, Collectors.toList()));

        for (Map.Entry<Long, List<ShopCartStatDto>> entry : map.entrySet()) {
            List<ShopCartStatDto> value = entry.getValue();
            LinkedHashMap<Long, List<ShopCartStatDto>> childMap = value.stream()
                    .collect(Collectors.groupingBy(ShopCartStatDto::getGoodsTypeId, LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<Long, List<ShopCartStatDto>> listEntry : childMap.entrySet()) {
                List<ShopCartStatDto> childValue = listEntry.getValue();
                for (ShopCartStatDto shopCart : childValue) {
                    List<Object> data = new ArrayList<>();
                    data.add(shopCart.getGoodsName());
                    data.add(shopCart.getGoodsTypeName());
                    data.add(shopCart.getStoreName());
                    data.add(storeOperationTypeMap.get(shopCart.getStoreUid()));
                    data.add(shopCart.getCode());
                    data.add(shopCart.getType().equals(3) ? "赠品" : "商城下单");
                    data.add(shopCart.getUnitPrice());
                    data.add(shopCart.getBuyNum());
                    data.add(shopCart.getPrice());
                    data.add(shopCart.getPayTimes());

                    dataList.add(data);
                }
            }
            dataList.add(new ArrayList<>());
        }

        // 导出授权码
        String fileName = "商品的销售数量明细" + beginDate + "-" + endDate;
        EasyExcel.write(ExcelHandler.getOutputStream(fileName, response))
                .head(headList).sheet("商品的销售数量明细")
                .doWrite(dataList);
    }

}
